package iotwisp.school.api.controller.pc_admin.system;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import iotwisp.base.cqrs.BusinessException;
import iotwisp.base.orm.query.pagination.Pagination;
import iotwisp.base.rest.JSONResultDTO;
import iotwisp.base.rest.RestBaseController;
import iotwisp.base.util.JSONUtils;
import iotwisp.school.system.command.CreateFileSCmd;
import iotwisp.school.system.entity.File;
import iotwisp.school.system.qo.FileQO;
import iotwisp.school.system.service.FileService;

@RestController
@RequestMapping("/api/system/file")
public class FileController extends RestBaseController {

	@Autowired
	private FileService fileService;

	@GetMapping("/query")
	public ResponseEntity<JSONResultDTO> queryRole(@RequestParam(name = "qo") String qoJson)
			throws UnsupportedEncodingException {

		FileQO qo = JSONUtils.parseObject(URLDecoder.decode(qoJson, "UTF-8"), FileQO.class);

		switch (qo.getResultType()) {
		case FileQO.RESULT_TYPE_COUNT:
			Integer count = fileService.queryCount(qo);
			return ResponseEntity.ok(createSuccessResult(count));
		case FileQO.RESULT_TYPE_UNIQUE:
			File file = fileService.queryUnique(qo);
			return ResponseEntity.ok(createSuccessResult(file));
		case FileQO.RESULT_TYPE_LIST:
			List<File> files = fileService.queryList(qo);
			return ResponseEntity.ok(createSuccessResult(files));
		case FileQO.RESULT_TYPE_PAGINATION:
			Pagination pagination = fileService.queryPagination(qo);
			return ResponseEntity.ok(createSuccessResult(pagination));
		default:
			return ResponseEntity.badRequest()
					.body(createFailResult(BusinessException.NECESSARY_PARAM_NULL, "resultType值有误", null));
		}

	}

	@PostMapping("/create")
	public ResponseEntity<JSONResultDTO> createFile(@RequestBody CreateFileSCmd cmd) throws BusinessException {

		File file = fileService.createFile(cmd);
		return ResponseEntity.ok(createSuccessResult(file));
	}
}
